//
//  StartVC.swift
//  BasketballScorer
//
//  Created by hasx on 2023/11/2.
//

import UIKit

class StartVC: UIViewController {

    @IBOutlet weak var leftTeamLB: UILabel!
    
    @IBOutlet weak var rightTeamLB: UILabel!
    
    @IBOutlet weak var timeLB: UILabel!
    
    @IBOutlet weak var startBtn: UIButton!
  
    @IBOutlet weak var resetBtn: UIButton!
    
    var MatchTimer:Timer?
    var hour:String = "00"
    var minutes:String = "00"
    var seconds:String = "00"
    var showTime:Int = 0
    
    var isTimerPaused = false
    
    var isReset = false

    override func viewDidLoad() {
        super.viewDidLoad()

        startBtn.layer.cornerRadius = 10;
        startBtn.layer.masksToBounds = true
        
        resetBtn.layer.cornerRadius = 10
        resetBtn.layer.masksToBounds = true
        self.initTimerMethod()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.resetMethod()

    }
    
    @IBAction func startBtnClick(_ sender: Any) {
        if startBtn.isSelected {
            startBtn.isSelected = false
            isTimerPaused = false
        }else{
            startBtn.isSelected = true
            isTimerPaused = true
            if isReset {
                isReset = false
                self.initTimerMethod()
            }
        }
        
    }
    
    func initTimerMethod(){
        MatchTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
    }
    
    @objc func timerFired(){
        if isTimerPaused == false{
            return
        }
        showTime += 1
        seconds = String(showTime % 60)
        minutes = String(showTime/(60*60))
        hour = String(showTime/(60*60*60))
        timeLB.text = "0\(hour):0\(minutes):\(seconds)"
    }
    
    
    @IBAction func resetBtnClick(_ sender: Any) {
        self.resetMethod()
    }
    
    func resetMethod(){
        isTimerPaused = false
        MatchTimer?.fire()
        MatchTimer?.invalidate()
        timeLB.text = "00:00:00"
        startBtn.isSelected = false
        MatchTimer = nil // 清理计时器对象
        isReset = true
        showTime = 0
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
